package com.angel.bo.message.config.aspect;


import com.angel.bo.common.util.JsonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 16:37 2017/12/6
 */
public class LogAspectController {
    private static final Logger logger = LoggerFactory.getLogger(LogAspectService.class);

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Pointcut("execution(public * com.angel.bo.message.controller..*.*(..))")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.info("[LogAspectController]--Start-[URL:{}],[HTTP_METHOD:{}],[IP:{}],[CLASS_METHOD:{}],[ARGS:{}]",
                request.getRequestURL().toString(),
                request.getMethod(),
                request.getRemoteAddr(),
                joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(),
                Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        logger.info("[LogAspectController]--End-[RESPONSE:{}],[SPEND TIME:{}]",
                JsonUtil.toJson(ret),
                System.currentTimeMillis() - startTime.get());
        startTime.remove();
    }



    @SuppressWarnings("ALL")
    @Around("execution(public * com.angel.bo.message.controller..*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint pjd) throws Throwable {
        Object result = null;
        String methodName = pjd.getSignature().getName();
        // 执行目标方法
        try {
            // 前置通知
            result = pjd.proceed();
            // 返回通知
        } catch (Throwable e) {
            // 异常通知
            logger.error(methodName  + "exception : " + e);
            throw e;
        }
        // 后置通知
        logger.info("The method " + methodName + " ends");
        return result;
    }


}
